package com.db.priceApp.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

import com.db.priceApp.domain.clientDataBasa.ClientProfile;
import com.db.priceApp.network.protocol.MessageTranciever;
import com.db.priceApp.service.MessageCostructor;

public class ClientMarketDataRequestsWriter implements Runnable {
	
	private volatile MessageTranciever mt;
	private volatile ClientProfile clientProfile;
	private volatile SelectionKey key;
	private volatile String userCommand;
	private volatile BufferedReader br = new BufferedReader(new InputStreamReader(
			System.in));
	private volatile Logger logger = Logger
			.getLogger(ClientMarketDataRequestsWriter.class.getName());
	private FileHandler file;

	public ClientMarketDataRequestsWriter(ClientProfile client) {
		clientProfile = client;
		key = clientProfile.getSelectionKey();
		mt = new MessageTranciever();
		try {
			file = new FileHandler("clientFile.log", true);
			logger.addHandler(file);
		} catch (SecurityException e) {
			logger.warning("fail to open file for logging");
		} catch (IOException e) {
			logger.warning("fail to open file for logging");
		}
	}

	private void sendLoginMessage(String login) {

		byte[] newOrder = MessageCostructor.createLoginReportMessage(login);
		clientProfile.setLogin(login);
		try {
			mt.transmit(newOrder, (SocketChannel) key.channel());
		} catch (IOException e) {
			logger.severe("client failure: " + e.getMessage());
			throw new RuntimeException("client error", e);
		}
	}

	@Override
	public void run() {
		try {
			do {
				System.out.println("input the login > ");
				userCommand = br.readLine();
			} while (userCommand.equals(""));
			sendLoginMessage(userCommand);

			byte[] newOrder;
			do {
				System.out.println("input the operation (s/u) > ");
				userCommand = br.readLine();
				System.out.println("input name of the instrument > ");
				String instrName = br.readLine();

				switch (userCommand) {
				case "s":
					newOrder = MessageCostructor
							.createSubscribeRequest(instrName);
					break;
				case "u":
					newOrder = MessageCostructor
							.createUnsubscribeRequest(instrName);
					break;
				case "exit":
					return;
				default:
					logger.warning("wrong operation " + userCommand);
					continue;
				}

				if (instrName.equals("")) {
					logger.warning("empty tag name");
					continue;
				}

				mt.transmit(newOrder, (SocketChannel) key.channel());

			} while (!userCommand.equals("exit"));
		} catch (IOException e) {
			logger.severe("client failure: " + e.getMessage());
			throw new RuntimeException("client error", e);
		}
	}

}
